// var loadWebIndex = null;
// layui.use(['layer'], function () {
//     var layer = layui.layer;
//     loadWebIndex = layer.load(1, {
//         shade: [0.1,'#fff'] //0.1透明度的白色背景
//     });
// });
/* 显示遮罩层 */
function showOverlay() {
    var overlay = $("#overlay");
    overlay.height(document.body.scrollHeight);
    overlay.width(document.body.scrollWidth);

    // fadeTo第一个参数为速度，第二个为透明度
    // 多重方式控制透明度，保证兼容性，但也带来修改麻烦的问题
    overlay.fadeTo(200, 0.5);
}
showOverlay();
/* 隐藏覆盖层 */
function hideOverlay() {
    $("#overlay").fadeOut(200);
}

$(function () {
   obj.init();
});
var obj = new function () {
    'use strict';
    return {
        form:null,
        tabs:null,
        editIndex:null,
        tchHistory:[
            // {sStartTime:'1995-12',sEndTime:'1998-12',sName:'蓝翔学院',sExtraName:'拖拉机',sMajor:'拖拉机专业',mDesc:'拖拉机专业资格证'},
            // {sStartTime:'1998-12',sEndTime:'2004-12',sName:'资深蓝翔学院',sExtraName:'资深拖拉机',sMajor:'资深拖拉机专业',mDesc:'资深拖拉机专业资格证'},
            // {sStartTime:'2004-12',sEndTime:'2016-12',sName:'高级蓝翔学院',sExtraName:'高级拖拉机',sMajor:'高级拖拉机专业',mDesc:'高级拖拉机专业资格证'}
        ],
        workHistory:[
            // {sStartTime:'1995-12',sEndTime:'1998-12',sName:'蓝翔拖拉机公司',sExtraName:'拖拉机攻城狮',sCertifier:'蓝翔高级教师',sPhone:'123456',mDesc:'与公司理念不和'}
        ],
        itemHistory:[
            // {sStartTime:'1995-12',sEndTime:'1998-12',sName:'项目实测',mDesc:'该开发项目即为严格'}
        ],
        family:[
            // {sRelation:'父子',sName:'dsa',sCompany:'dasd',sPhone:'1232'}
        ],
        init:function () {
            this.tabs = $('.tabs').eq(0);
            this.funObj().onLoadSuccess();
            this.listener();
        },
        listener:function () {
            var $this = this;
            //上一步
            $('#preStep').on('click',function () {
                $this.funObj().goToPrev();
            });
            //下一步
            $('#nextStep').on('click',function () {
                $this.funObj().goToNext();
            });

            $("#iEmploySource").combobox({
                onChange:function (val) {
                    console.log(val);
                   if (val != 4) {
                       $('#staff').hide();
                   } else {
                       $('#staff').show();
                   }
                }
            });

            $('#save').click(function () {
                $this.funObj().saveInfo();
            })
        },
        funObj:function () {
            var $this = this;
            return {
                onLoadSuccess:function () {
                    $('.tabs-wrap').eq(0).hide();
                    // var dom = $('<div style="height: 35px;background-color: white;position: absolute;left: 0;bottom: 0px;right: 0px;"> <a id="preStep" class="easyui-linkbutton pull-left" style="width:80px;margin-left: 10px;">上一步</a><a id="nextStep" class="easyui-linkbutton pull-right" style="width:80px;margin-right: 10px;">下一步</a></div>');
                    // $('.easyui-tabs').eq(0).append(dom);
                    // $.parser.parse(dom);
                    $this.funObj().checkEnable();
                    hideOverlay();
                    $this.funObj().loadTchHistory();
                    $this.funObj().loadWorkHistory();
                    $this.funObj().loadItemHistory();
                    $this.funObj().loadFamily();

                    $('#iRecStaff').combobox({
                        url:baseUrl+'hrm/interview/getStaff',
                        mode:'remote',
                        method:'post',
                        textField:'sStaffName',
                        valueField:'iStaffId'
                    });
                    monthFormat();
                },
                goToPrev:function () {
                    var prevDom = $this.tabs.find('.tabs-selected').prev().find('a');
                    if (prevDom.length > 0) {
                        prevDom.click();
                    }
                    $this.funObj().checkEnable();
                    $this.funObj().setMainTitle();
                },
                goToNext:function () {
                    var nextDom = $this.tabs.find('.tabs-selected').next().find('a');
                    if (nextDom.length > 0) {
                        nextDom.click();
                    }
                    $this.funObj().checkEnable();
                    $this.funObj().setMainTitle();
                },
                checkEnable:function () {
                    var prevDom = $this.tabs.find('.tabs-selected').prev().find('a');
                    var nextDom = $this.tabs.find('.tabs-selected').next().find('a');
                    if (prevDom.length > 0) {
                        if (xhExtra.buttonDisabled($('#preStep'))) {
                            xhExtra.enableButton($('#preStep'), 'eu');
                        }
                    } else {
                        xhExtra.disableButton($('#preStep'), 'eu');
                    }
                    if (nextDom.length > 0) {
                        if (xhExtra.buttonDisabled($('#nextStep'))) {
                            xhExtra.enableButton($('#nextStep'), 'eu');
                        }
                    } else{
                        xhExtra.disableButton($('#nextStep'), 'eu');
                    }
                },
                setMainTitle:function () {
                    var tab = $this.tabs.find('.tabs-selected');
                    $('#mainPanel-title').html(tab.eq(0).text());
                },
                addForm:function (tag) {
                    $this.funObj().goTo(tag,'slide','right');
                    var form = $(tag).find('form');
                    form.form('clear');
                },
                editForm:function (tag,index) {
                    $this.funObj().goTo(tag,'slide','right');
                    var form = $(tag).find('form');
                    form.form('clear');
                    $this.editIndex = index + 1;
                    if (tag == '#tchPanel') {
                        $this.funObj().fillData(form, $this.tchHistory[index]);
                    } else if (tag == '#workPanel') {
                        $this.funObj().fillData(form, $this.workHistory[index]);
                    } else if (tag == '#itemPanel') {
                        $this.funObj().fillData(form, $this.itemHistory[index]);
                    } else if (tag == '#contactPanel') {
                        $this.funObj().fillData(form, $this.family[index]);
                    }
                },
                saveTch:function () {
                    var params = $('#tchPanel').find('form').serialize();
                        params = decodeURIComponent(params, true);
                        params = strToObj(params);
                    askConfirm('确认要保存么?',function () {
                        if (!$this.editIndex) { //保存
                            $this.tchHistory.push(params);
                        } else { //编辑
                            $this.tchHistory[$this.editIndex-1] = params;
                        }
                        $this.funObj().loadTchHistory();
                        $("#tchBack").click();
                    });
                },
                saveWork:function () {
                    var params = $('#workPanel').find('form').serialize();
                    params = decodeURIComponent(params, true);
                    params = strToObj(params);
                    askConfirm('确认要保存么?',function () {
                        if (!$this.editIndex) { //保存
                            $this.workHistory.push(params);
                        } else { //编辑
                            $this.workHistory[$this.editIndex-1] = params;
                        }
                        $this.funObj().loadWorkHistory();
                        $("#workBack").click();
                    });
                },
                saveItem:function () {
                    var params = $('#itemPanel').find('form').serialize();
                    params = decodeURIComponent(params, true);
                    params = strToObj(params);
                    askConfirm('确认要保存么?',function () {
                        if (!$this.editIndex) { //保存
                            $this.itemHistory.push(params);
                        } else { //编辑
                            $this.itemHistory[$this.editIndex-1] = params;
                        }
                        $this.funObj().loadItemHistory();
                        $("#itemBack").click();
                    });
                },
                saveContact:function () {
                    var params = $('#contactPanel').find('form').serialize();
                    params = decodeURIComponent(params, true);
                    params = strToObj(params);
                    askConfirm('确认要保存么?',function () {
                        if (!$this.editIndex) { //保存
                            $this.family.push(params);
                        } else { //编辑
                            $this.family[$this.editIndex-1] = params;
                        }
                        $this.funObj().loadFamily();
                        $("#familyBack").click();
                    });
                },
                goTo:function (id) {
                    $.mobile.go(id);
                    $this.editIndex = null;
                },
                fillData:function (form,data) { //赋值
                    $.each(data,function (key,value) {
                        var dom = form.find('.'+key);
                        if (dom.length > 0) {
                            var easyType = dom[0].classList[0].split('-')[1];
                            if (easyType == 'datebox') {
                                dom.datebox('setValue',value);
                            } else if (easyType == 'textbox') {
                                dom.textbox('setValue',value);
                            }
                        }
                    });
                },
                loadTchHistory:function () {
                    var str = '';
                    if ($this.tchHistory.length > 0) {
                        $.each($this.tchHistory,function (index,row) {
                            str+='<li class="layui-timeline-item">\n' +
                                '                        <i class="layui-icon layui-timeline-axis"></i>\n' +
                                '                        <div class="layui-timeline-content layui-text">\n' +
                                '                            <h3 class="layui-timeline-title">'+row['sStartTime']+'至'+ (row['sEndTime'] ? row['sEndTime'] : '至今') +'<a class="pull-right btn-sm" onclick="obj.funObj().delArray(\'tchHistory\','+index+')" style="color: red"><i class="fa fa-trash fa-sm "></i>删除</a><a class="pull-right btn-sm" onclick="obj.funObj().editForm(\'#tchPanel\','+index+')"><i class="fa fa-pencil fa-sm "></i>编辑</a></h3>\n' +
                                '                            <p style="font-size: medium">学校名称：'+row['sName']+'</p>\n' +
                                '                            <p style="font-size: medium">学位：'+row['sExtraName']+'</p>\n' +
                                '                            <p style="font-size: medium">专业：'+row['sMajor']+'</p>\n' +
                                '                            <p>\n' +
                                '                                获得途径：<br>' + row['mDesc']+
                                '                            </p>\n' +
                                '                            <hr>\n' +
                                '                        </div>\n' +
                                '                    </li>';
                        });
                    }
                    str += '<li class="layui-timeline-item">\n' +
                        '                        <div class="layui-timeline-content layui-text">\n' +
                        '                            <div class="layui-timeline-title" style="text-align: center"><a class=" btn-sm" onclick="obj.funObj().addForm(\'#tchPanel\')" style="color: black;display: block;width: 100%"><i class="fa fa-plus fa-sm " style="color: orange" ></i>&nbsp;&nbsp;新增教育经历</a></div>\n' +
                        '                        </div>\n' +
                        '                    </li>';
                    $('#tchHistory').empty().append(str);
                },
                loadWorkHistory:function () {
                    var str = '';
                    if ($this.workHistory.length > 0) {
                        $.each($this.workHistory,function (index,row) {
                            str+='<li class="layui-timeline-item">\n' +
                                '                        <i class="layui-icon layui-timeline-axis"></i>\n' +
                                '                        <div class="layui-timeline-content layui-text">\n' +
                                '                            <h3 class="layui-timeline-title">'+row['sStartTime']+'至'+ (row['sEndTime'] ? row['sEndTime'] : '至今') +'<a class="pull-right btn-sm" onclick="obj.funObj().delArray(\'workHistory\','+index+')" style="color: red"><i class="fa fa-trash fa-sm "></i>删除</a><a class="pull-right btn-sm" onclick="obj.funObj().editForm(\'#workPanel\','+index+')"><i class="fa fa-pencil fa-sm "></i>编辑</a></h3>\n' +
                                '                            <p style="font-size: medium">公司名称:'+row['sName']+'</p>\n' +
                                '                            <p style="font-size: medium">职位：'+row['sExtraName']+'</p>\n' +
                                '                            <p style="font-size: medium" >证明人：'+row['sCertifier']+ (row['sPhone'] ?  '('+row['sPhone']+')' : '' )+'</p>\n' +
                                '                            <p>离职原因:<br>\n' +
                                '                                 ' + row['mDesc']+
                                '                            </p>\n' +
                                '                            <hr>\n' +
                                '                        </div>\n' +
                                '                    </li>';
                        });
                    }
                    str += '<li class="layui-timeline-item">\n' +
                        '                        <div class="layui-timeline-content layui-text">\n' +
                        '                            <div class="layui-timeline-title" style="text-align: center"><a class=" btn-sm" onclick="obj.funObj().addForm(\'#workPanel\')" style="color: black;display: block;width: 100%"><i class="fa fa-plus fa-sm " style="color: orange" ></i>&nbsp;&nbsp;新增工作经历</a></div>\n' +
                        '                        </div>\n' +
                        '                    </li>';
                    $('#workHistory').empty().append(str);
                },
                loadItemHistory:function () {
                    var str = '';
                    if ($this.itemHistory.length > 0) {
                        $.each($this.itemHistory,function (index,row) {
                            str+='<li class="layui-timeline-item">\n' +
                                '                        <i class="layui-icon layui-timeline-axis"></i>\n' +
                                '                        <div class="layui-timeline-content layui-text">\n' +
                                '                            <h3 class="layui-timeline-title">'+row['sStartTime']+'至'+ (row['sEndTime'] ? row['sEndTime'] : '至今') +'<a class="pull-right btn-sm" onclick="obj.funObj().delArray(\'itemHistory\','+index+')" style="color: red"><i class="fa fa-trash fa-sm "></i>删除</a><a class="pull-right btn-sm" onclick="obj.funObj().editForm(\'#itemPanel\','+index+')"><i class="fa fa-pencil fa-sm "></i>编辑</a></h3>\n' +
                                '                            <p style="font-size: medium">项目名称:'+row['sName']+'</p>\n' +
                                '                            <p>描述:<br>\n' +
                                '                                 ' + row['mDesc']+
                                '                            </p>\n' +
                                '                            <hr>\n' +
                                '                        </div>\n' +
                                '                    </li>';
                        });
                    }
                    str += '<li class="layui-timeline-item">\n' +
                        '                        <div class="layui-timeline-content layui-text">\n' +
                        '                            <div class="layui-timeline-title" style="text-align: center"><a class=" btn-sm" onclick="obj.funObj().addForm(\'#itemPanel\')" style="color: black;display: block;width: 100%"><i class="fa fa-plus fa-sm " style="color: orange" ></i>&nbsp;&nbsp;新增重要项目经历</a></div>\n' +
                        '                        </div>\n' +
                        '                    </li>';
                    $('#itemHistory').empty().append(str);
                },
                loadFamily:function () {
                    var str = '';
                    if ($this.family.length > 0) {
                        $.each($this.family,function (index,row) {
                            str+='<li class="layui-timeline-item">\n' +
                                '                        <i class="layui-icon layui-timeline-axis"></i>\n' +
                                '                        <div class="layui-timeline-content layui-text">\n' +
                                '                            <h3 class="layui-timeline-title">'+row['sRelation'] +'<a class="pull-right btn-sm" onclick="obj.funObj().delArray(\'family\','+index+')" style="color: red"><i class="fa fa-trash fa-sm "></i>删除</a><a class="pull-right btn-sm" onclick="obj.funObj().editForm(\'#contactPanel\','+index+')"><i class="fa fa-pencil fa-sm "></i>编辑</a></h3>\n' +
                                '                            <p style="font-size: medium">名字:'+row['sName']+'</p>\n' +
                                '                            <p style="font-size: medium">联系电话:'+row['sPhone']+'</p>\n' +
                                '                            <p style="font-size: medium">工作单位:'+row['sCompany']+'</p>\n' +
                                '                            <hr>\n' +
                                '                        </div>\n' +
                                '                    </li>';
                        });
                    }
                    str += '<li class="layui-timeline-item">\n' +
                        '                        <div class="layui-timeline-content layui-text">\n' +
                        '                            <div class="layui-timeline-title" style="text-align: center"><a class=" btn-sm" onclick="obj.funObj().addForm(\'#contactPanel\')" style="color: black;display: block;width: 100%"><i class="fa fa-plus fa-sm " style="color: orange" ></i>&nbsp;&nbsp;新增联系人</a></div>\n' +
                        '                        </div>\n' +
                        '                    </li>';
                    $('#family').empty().append(str);
                },
                delArray:function (tag,index) {
                    askConfirm('确认要删除吗?',function () {
                        if (tag == 'tchHistory') {
                            var array = $this.tchHistory;
                            array.splice(index, 1);
                            $this.funObj().loadTchHistory();
                        } else if (tag == 'workHistory') {
                            var array = $this.workHistory;
                            array.splice(index, 1);
                            $this.funObj().loadWorkHistory();
                        } else if (tag == 'itemHistory') {
                            var array = $this.itemHistory;
                            array.splice(index, 1);
                            $this.funObj().loadItemHistory();
                        } else if (tag == 'family') {
                            var array = $this.family;
                            array.splice(index, 1);
                            $this.funObj().loadFamily();
                        }
                    });
                },
                collectData:function () {
                    var baseInfo = $('#form').serialize();
                    baseInfo = decodeURIComponent(baseInfo, true);
                    baseInfo = strToObj(baseInfo);
                    baseInfo.tchHistory = $this.tchHistory;
                    baseInfo.workHistory = $this.workHistory;
                    baseInfo.itemHistory = $this.itemHistory;
                    baseInfo.family = $this.family;
                    return baseInfo;
                },
                calculateInfo:function () {
                    var $data = $this.funObj().collectData();
                    var $count = 0;
                    var $setCount = 0;
                    $.each($data, function (key,value) {
                        $count++;
                        if (value) {
                            $setCount++;
                        }
                    });
                    return $setCount/$count;
                },
                saveInfo:function () {
                    var $calRate = $this.funObj().calculateInfo();
                    if ($calRate > 0.95) {
                        $this.funObj().save();
                    } else {
                        askConfirm('信息未填写完整?确认要提交么',function () {
                            $this.funObj().save();
                        })
                    }
                },
                save:function () {
                    $.ajax({
                        url: baseUrl + 'hrm/interview/saveSource',
                        type: 'POST',
                        data: $this.funObj().collectData(),
                        dataType: 'json',
                        complete: function(XMLHttpRequest){
                            var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                            if (result.code == 200) {
                                showSuccess(result.msg);
                            } else {
                                showError(result.error)
                            }
                        }
                    });
                }

            }
        }
    }
};

/**
 * form serilize() 对象转obj
 *
 * @param str
 * @returns {any}
 */
function strToObj(str){
    str = str.replace(/&/g,"','");
    str = str.replace(/=/g,"':'");
    str = "({'"+str +"'})";
    return  eval(str);
}

/**
 * 询问
 *
 * @param title
 * @param callback
 *
 */
function askConfirm(title,callback) {
    swal({
        title:title,
        type: 'info',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        onOpen:function () {
            if ($('.swal2-spacer').length > 0) {
                $('.swal2-spacer').hide();
            }
        }
    }).then(function () {
        if(callback){
            callback.call(this);
        }
    },function () {
        return false;
    });
}

function showSuccess(title) {
    swal({
        title:title,
        type: 'success',
        confirmButtonText: '确定',
        onOpen:function () {
            if ($('.swal2-spacer').length > 0) {
                $('.swal2-spacer').hide();
            }
        }
    }).then(function () {
        return false;
    },function () {
        return false;
    });
}
function showError(msg) {
    swal({
        title:msg,
        type: 'error',
        confirmButtonText: '确定',
        onOpen:function () {
            if ($('.swal2-spacer').length > 0) {
                $('.swal2-spacer').hide();
            }
        }
    }).then(function () {
        return false;
    },function () {
        return false;
    });
}

/**
 * easyui 日期格式只要年月
 *
 *
 */
function monthFormat() {
    //日期选择对象
    $('.month').datebox({
        //显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
        onShowPanel: function () {
            //触发click事件弹出月份层
            var p = $(this).datebox('panel'),
                //日期选择对象中月份
                tds = false,
                //显示月份层的触发控件
                span = p.find('span.calendar-text'),
                kthis = $(this);
            span.trigger('click');
            if (!tds)
            //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                setTimeout(function() {
                    tds = p.find('div.calendar-menu-month-inner td');
                    tds.click(function(e) {
                        //禁止冒泡执行easyui给月份绑定的事件
                        e.stopPropagation();
                        var month = parseInt($(this).attr('abbr'), 10);
                        var year = p.find('.calendar-menu-year').val();
                        //隐藏日期对象
                        kthis.datebox('hidePanel')
                        //设置日期的值
                            .datebox('setValue', year + '-' + month);
                    });
                }, 0);
        },
        //配置parser，返回选择的日期
        parser: function (s) {
            if (!s) return new Date();
            var arr = s.split('-');
            return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
        },
        //配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth());
        formatter: function (d) {
            var currentMonth = (d.getMonth()+1);
            var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
            return d.getFullYear() + '-' + currentMonthStr;
        }
    });
}